<i18n locale="zh-CN" lang="yaml">
Add Blueprint  : 添加蓝图
Setup Blueprint: 配置蓝图

Blueprint ID will be used as Script Set ID after deployment: 蓝图 ID 在部署后将作为脚本集 ID

Please input ID                                   : 请输入 ID
Only alphabets, numbers and underscore are allowed: 只能包含大小写英文、数字及下划线
Cannot not starts with a number                   : 不得以数字开头
'ID cannot contains double underscore "__"'       : '不能包含双下划线 "__"'

Blueprint created: 蓝图已创建
Blueprint saved  : 蓝图已保存
Blueprint deleted: 蓝图已删除

Are you sure you want to delete the Blueprint?: 是否确认删除此蓝图？
</i18n>

<!-- Generated by OpenCC START -->
<i18n locale="zh-HK" lang="yaml">
Add Blueprint: 添加藍圖
Are you sure you want to delete the Blueprint?: 是否確認刪除此藍圖？
Blueprint ID will be used as Script Set ID after deployment: 藍圖 ID 在部署後將作為腳本集 ID
Blueprint created: 藍圖已創建
Blueprint deleted: 藍圖已刪除
Blueprint saved: 藍圖已保存
Cannot not starts with a number: 不得以數字開頭
ID cannot contains double underscore "__": 不能包含雙下劃線 "__"
Only alphabets, numbers and underscore are allowed: 只能包含大小寫英文、數字及下劃線
Please input ID: 請輸入 ID
Setup Blueprint: 配置藍圖
</i18n>
<i18n locale="zh-TW" lang="yaml">
Add Blueprint: 新增藍圖
Are you sure you want to delete the Blueprint?: 是否確認刪除此藍圖？
Blueprint ID will be used as Script Set ID after deployment: 藍圖 ID 在部署後將作為指令碼集 ID
Blueprint created: 藍圖已建立
Blueprint deleted: 藍圖已刪除
Blueprint saved: 藍圖已儲存
Cannot not starts with a number: 不得以數字開頭
ID cannot contains double underscore "__": 不能包含雙下劃線 "__"
Only alphabets, numbers and underscore are allowed: 只能包含大小寫英文、數字及下劃線
Please input ID: 請輸入 ID
Setup Blueprint: 配置藍圖
</i18n>
<!-- Generated by OpenCC END -->

<template>
  <el-dialog
    id="ScriptSetSetup"
    :visible.sync="show"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    width="750px">

    <template slot="title">
      {{ pageTitle }} <code class="text-main" v-if="pageMode === 'setup'">{{ data.title || data.id }}</code>
    </template>

    <el-container direction="vertical">
      <el-main>
        <div class="setup-form">
          <el-form ref="form" label-width="135px" :model="form" :rules="formRules">
            <el-form-item label="ID" prop="id">
              <el-input :disabled="pageMode === 'setup'"
                maxlength="60"
                v-model="form.id"></el-input>
              <InfoBlock :title="$t('Blueprint ID will be used as Script Set ID after deployment')" />
            </el-form-item>

            <el-form-item :label="$t('Title')">
              <el-input :placeholder="$t('Optional')"
                maxlength="200"
                v-model="form.title"></el-input>
            </el-form-item>

            <el-form-item :label="$t('Description')">
              <el-input :placeholder="$t('Optional')"
                type="textarea"
                resize="none"
                :autosize="{minRows: 2}"
                maxlength="5000"
                v-model="form.description"></el-input>
            </el-form-item>

            <el-form-item class="setup-footer">
              <el-link type="danger" class="float-left" v-if="pageMode === 'setup'" @click="deleteData">{{ $t('Delete') }}</el-link>
              <el-button type="primary" v-prevent-re-click @click="submitData">{{ $t('Save') }}</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-main>
    </el-container>
  </el-dialog>
</template>

<script>
export default {
  name: 'BlueprintSetup',
  components: {
  },
  watch: {
    show(val) {
      if (!val) {
        this.$root.$emit('reload.blueprintList');
      }
    },
  },
  methods: {
    async loadData(id) {
      if (!id) {
        this.pageMode = 'add';
        this.T.jsonClear(this.form);
        this.data = {};

      } else {
        this.pageMode = 'setup';
        this.data.id = id;

        let apiRes = await this.T.callAPI_getOne('/api/v1/blueprints/do/list', this.data.id);
        if (!apiRes || !apiRes.ok) return;

        this.data = apiRes.data;

        let nextForm = {};
        Object.keys(this.form).forEach(f => nextForm[f] = this.data[f]);
        this.form = nextForm;
      }

      this.show = true;
    },
    async submitData() {
      try {
        await this.$refs.form.validate();
      } catch(err) {
        return console.error(err);
      }

      switch(this.pageMode) {
        case 'add':
          return await this.addData();
        case 'setup':
          return await this.modifyData();
      }
    },
    async addData() {
      let apiRes = await this.T.callAPI('post', '/api/v1/blueprints/do/add', {
        body    : { data: this.T.jsonCopy(this.form) },
        feedback: { okMessage: this.$t('Blueprint created') },
      });
      if (!apiRes || !apiRes.ok) return;

      let nextRouteQuery = this.T.packRouteQuery();

      this.$store.commit('updateHighlightedTableDataId', apiRes.data.id);
      this.show = false;

      this.$router.push({
        name  : 'blueprint-canvas',
        params: { id: apiRes.data.id },
        query : nextRouteQuery,
      });
    },
    async modifyData() {
      let _formData = this.T.jsonCopy(this.form);
      delete _formData.id;

      let apiRes = await this.T.callAPI('post', '/api/v1/blueprints/:id/do/modify', {
        params  : { id: this.data.id },
        body    : { data: _formData },
        feedback: { okMessage: this.$t('Blueprint saved') },
      });
      if (!apiRes || !apiRes.ok) return;

      this.$store.commit('updateHighlightedTableDataId', apiRes.data.id);
      this.show = false;
    },
    async deleteData() {
      if (!await this.T.confirm(this.$t('Are you sure you want to delete the Blueprint?'))) return;

      let apiRes = await this.T.callAPI('/api/v1/blueprints/:id/do/delete', {
        params  : { id: this.data.id },
        feedback: { okMessage: this.$t('Blueprint deleted') },
      });
      if (!apiRes || !apiRes.ok) return;

      this.show = false;
    },
  },
  computed: {
    pageTitle() {
      const _map = {
        setup: this.$t('Setup Blueprint'),
        add  : this.$t('Add Blueprint'),
      };
      return _map[this.pageMode];
    },
  },
  data() {
    return {
      show    : false,
      pageMode: null,

      data: {},
      form: {
        id         : null,
        title      : null,
        description: null,
      },
      formRules: {
        id: [
          {
            trigger : 'blur',
            message : this.$t('Please input ID'),
            required: true,
          },
          {
            trigger: 'change',
            message: this.$t('Only alphabets, numbers and underscore are allowed'),
            pattern: /^[a-zA-Z0-9_]*$/g,
          },
          {
            trigger: 'change',
            message: this.$t('Cannot not starts with a number'),
            pattern: /^[^0-9]/g,
          },
          {
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (value && value.indexOf('__') >= 0) {
                let _message = this.$t('ID cannot contains double underscore "__"');
                return callback(new Error(_message));
              }
              return callback();
            },
          },
        ],
      }
    }
  },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
